/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package emergence.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import util.Logger;

/**
 *
 * @author Nathan Templon
 */
public class WorldServer extends Thread {

    private static int serverNumber = 0;
    private static final Logger logger = Logger.getDefaultLogger();
    
    boolean running;
    
    private final int portNumber;
    private ServerSocket server;
    private Socket client;
    
    private PrintWriter out;
    private BufferedReader in;
    
    private WorldProtocol protocol;

    public WorldServer(int port) {
        super("World Server " + serverNumber);
        serverNumber++;
        
        this.portNumber = port;
        protocol = new WorldProtocol();
    }

    @Override
    public void run() {
        try {
            server = new ServerSocket(portNumber);
            client = server.accept();
            
            out = new PrintWriter(client.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            
            String inputLine, outputLine;
            running = true;
            
            while ((inputLine = in.readLine()) != null) {
                outputLine = protocol.getResponse(inputLine);
                if (outputLine != null) {
                    out.println(outputLine);
                }
            }
            out.close();
            in.close();
            client.close();
            server.close();
        }
        catch (IOException ex) {
            System.out.println(ex);
            logger.log(ex);
        }
    }

}
